package com.jack006.api;

import com.jack006.exception.GraceException;
import com.jack006.grace.result.GraceJSONResult;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.Category;
import com.jack006.utils.JsonUtils;
import com.jack006.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname BaseController
 * @Description 基本 controller
 * @Date 2021-06-13 14:37
 * @Created by jack
 */
public class BaseController {

    @Autowired
    public RedisOperator redisOperator;
    @Autowired
    public RestTemplate restTemplate;

    public static final String MOBILE_SMSCODE = "mobile:smscode";
    public static final String REDIS_USER_TOKEN = "redis_user_token";
    public static final String REDIS_ADMIN_TOKEN = "redis_admin_token";
    public static final String REDIS_USER_INFO = "redis_user_info";
    public static final String REDIS_ALL_CATEGORY = "redis_all_category";
    public static final String REDIS_WRITER_FANS_COUNTS = "redis_writer_fans_counts";
    public static final String REDIS_MY_FOLLOW_COUNTS = "redis_my_follow_counts";

    public static final String REDIS_ARTICLE_READ_COUNTS = "redis_article_read_counts";
    public static final String REDIS_ARTICLE_COMMENTS_COUNTS = "redis_article_comments_counts";
    public static final String REDIS_ALREADY_READ = "redis_already_read";



    @Value("${website.domain-name}")
    private String DOMAIN_NAME;

    public static final Integer COOKIE_MONTH = 30 * 24 * 60 * 60;
    public static final Integer COOKIE_DELETE = 0;


    public static final Integer COMMON_START_PAGE = 1;
    public static final Integer COMMON_PAGE_SIZE = 10;

    /**
     * 获取 BO 中的错误信息
     * @param result
     */
//    public Map<String,String> getErrors(BindingResult result) {
//        List<FieldError> fieldErrors = result.getFieldErrors();
//        // 发送验证错误的时候所对应的某个属性  验证的错误信息
//        Map<String,String> map = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
//        return map;
//    }

    /**
     * 设置 cookie
     * @param request
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param maxAge
     */
    public void setCookie(HttpServletRequest request,
                          HttpServletResponse response,
                          String cookieName,
                          String cookieValue,
                          Integer maxAge) {
        try {
            cookieValue = URLEncoder.encode(cookieValue,"UTF-8");
            setCookieValue(request,response,cookieName,cookieValue,maxAge);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除 cookie
     * @param request
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param maxAge
     */
    public void setCookieValue(HttpServletRequest request,
                          HttpServletResponse response,
                          String cookieName,
                          String cookieValue,
                          Integer maxAge) {
        Cookie cookie = new Cookie(cookieName,cookieValue);
        cookie.setDomain(DOMAIN_NAME);
        // cookie.setDomain("jack006.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }


    public void deleteCookie(HttpServletRequest request,
                             HttpServletResponse response,
                             String cookieName) {
        try {
            String deleteValue = URLEncoder.encode("","UTF-8");
            setCookieValue(request,response,cookieName,deleteValue,COOKIE_DELETE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断文章领域是否存在
     * @param categoryId
     */
    public void checkCatIsExist(Integer categoryId) {
        String allCatJson = redisOperator.get(REDIS_ALL_CATEGORY);
        if (StringUtils.isBlank(allCatJson)) {
            GraceException.display(ResponseStatusEnum.SYSTEM_OPERATION_ERROR);
        }
        List<Category> categoryList = JsonUtils.jsonToList(allCatJson, Category.class);
        List<Category> collect = categoryList.stream().filter(t -> t.getId() == categoryId)
                .collect(Collectors.toList());
        if (collect == null && collect.isEmpty()) {
            GraceException.display((ResponseStatusEnum.ARTICLE_COVER_NOT_EXIST_ERROR));
        }
    }


    public Category getCategory(Integer categoryId) {
        String allCatJson = redisOperator.get(REDIS_ALL_CATEGORY);
        if (StringUtils.isBlank(allCatJson)) {
            GraceException.display(ResponseStatusEnum.SYSTEM_OPERATION_ERROR);
        }
        List<Category> categoryList = JsonUtils.jsonToList(allCatJson, Category.class);
        List<Category> collect = categoryList.stream().filter(t -> t.getId() == categoryId)
                .collect(Collectors.toList());
        if (collect == null && collect.isEmpty()) {
            GraceException.display((ResponseStatusEnum.ARTICLE_CATEGORY_NOT_EXIST_ERROR));
        }
        Category category = collect.get(0);
        return category;
    }

    public Integer getCountsFormRedis(String key) {
        String countStr = redisOperator.get(key);
        if (StringUtils.isBlank(countStr)) {
            countStr = "0";
        }
        return Integer.valueOf(countStr);
    }

    public GraceJSONResult globalFallBack() {
        System.out.println("全局降级");
        return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_ERROR_GLOBAL);
    }

}
